"""
邮件解析模块
功能：解析邮件正文、附件等
"""

import email
from email.header import decode_header
import logging

logger = logging.getLogger('email_system')


def parse_email_body(email_body_bytes):
    """
    解析邮件正文
    
    Args:
        email_body_bytes: 邮件原始字节内容
    
    Returns:
        (body_text, body_html, attachments)
    """
    try:
        email_message = email.message_from_bytes(email_body_bytes)
        
        body_text = ''
        body_html = ''
        attachments = []
        
        if email_message.is_multipart():
            for part in email_message.walk():
                content_type = part.get_content_type()
                content_disposition = str(part.get('Content-Disposition', ''))
                
                # 提取正文
                if 'attachment' not in content_disposition:
                    if content_type == 'text/plain' and not body_text:
                        try:
                            payload = part.get_payload(decode=True)
                            if payload:
                                charset = part.get_content_charset() or 'utf-8'
                                body_text = payload.decode(charset, errors='ignore')
                        except Exception as e:
                            logger.error(f"解析纯文本失败: {e}")
                    
                    elif content_type == 'text/html' and not body_html:
                        try:
                            payload = part.get_payload(decode=True)
                            if payload:
                                charset = part.get_content_charset() or 'utf-8'
                                body_html = payload.decode(charset, errors='ignore')
                        except Exception as e:
                            logger.error(f"解析HTML失败: {e}")
                
                # 提取附件信息
                elif 'attachment' in content_disposition or part.get_filename():
                    filename = part.get_filename()
                    if filename:
                        # 解码文件名
                        decoded = decode_header(filename)
                        if decoded[0][1]:
                            filename = decoded[0][0].decode(decoded[0][1])
                        else:
                            filename = decoded[0][0] if isinstance(decoded[0][0], str) else decoded[0][0].decode('utf-8', errors='ignore')
                        
                        payload = part.get_payload(decode=True)
                        attachments.append({
                            'filename': filename,
                            'content_type': content_type,
                            'size': len(payload) if payload else 0
                        })
        else:
            # 非multipart邮件
            content_type = email_message.get_content_type()
            try:
                payload = email_message.get_payload(decode=True)
                if payload:
                    charset = email_message.get_content_charset() or 'utf-8'
                    text = payload.decode(charset, errors='ignore')
                    
                    if content_type == 'text/html':
                        body_html = text
                    else:
                        body_text = text
            except Exception as e:
                logger.error(f"解析非multipart邮件失败: {e}")
        
        return body_text, body_html, attachments
    
    except Exception as e:
        logger.error(f"解析邮件失败: {e}")
        return '', '', []
